

#include <stdio.h>
#include <stdlib.h>

struct ListNode{
    int val;
    struct ListNode *next;
};

typedef struct ListNode Node, *pNode;

void print(struct ListNode* p)
{
	struct ListNode* q;
	for(q = p; q != NULL; q = q->next)
		printf("[%d]", q->val);
	printf("\n");
}

void setList(struct ListNode * p, int val)
{
	struct ListNode *q;
	q = p;
	while(q->next != NULL)
		q = q->next;
	
	struct ListNode *tmp = (struct ListNode *)malloc(sizeof(struct ListNode));
	if(tmp == NULL)
		return;
	tmp->val = val;
	tmp->next = q->next;
	q->next = tmp;
}

struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode* p, *q, *head;
	struct ListNode* pList1 = l1,* pList2 = l2;
	
	p = head = NULL;

	for(;;)
	{
		printf("%p %p\n", pList1, pList2);
		if(pList1 != NULL && pList2 != NULL)
		{
			q = (pList1->val < pList2->val)? pList1:pList2;
			if(p == NULL)
				head = p = q;
			else
			{
				p->next = q;
				p = p->next;
			}
			if(pList1 == q)
				pList1 = pList1->next;
			else 
				pList2 = pList2->next;
		}
		else if(pList1 != NULL)
		{
			q = pList1;
			if(p == NULL)
				head = p = q;
			else
			{
				p->next = q;
				p = p->next;
			}
			pList1 = pList1->next;
		}
		else if(pList2 != NULL)
		{
			q = pList2;
			if(p == NULL)
				head = p = q;
			else
			{
				p->next = q;
				p = p->next;
			}
			pList2 = pList2->next;
		}
		else
			break;
	}
	return head;
}

int main(void)
{
	struct ListNode* l1, *l2;
	int num[] = {2};
	int num1[] = {1};
	int val = 1;
	int i;
	//head = (struct ListNode *)malloc(sizeof(struct ListNode));
	//head->val = num[0];
	//head->next = NULL;
	l1 = (struct ListNode *)malloc(sizeof(struct ListNode));
	l1->val = num[0];
	l1->next = NULL;
	l2 = (struct ListNode *)malloc(sizeof(struct ListNode));
	l2->val = num1[0];
	l2->next = NULL;
	for(i = 1; i < sizeof(num)/sizeof(int); i++)
		setList(l1, num[i]);
	for(i = 1; i < sizeof(num1)/sizeof(int); i++)
		setList(l2, num[i]);
	print(l1);print(l2);
	print(mergeTwoLists(l1, l2));
	return 0;
}